use anyhow::Result;
use std::process::{Command, Stdio};
use std::thread;
use std::time::Duration;

mod comprehensive_test;
mod performance_test;
mod error_scenario_test;

use comprehensive_test::ComprehensiveTestSuite;
use performance_test::PerformanceTestSuite;
use error_scenario_test::ErrorScenarioTestSuite;

/// 测试运行器
pub struct TestRunner {
    server_process: Option<std::process::Child>,
}

impl TestRunner {
    pub fn new() -> Self {
        Self {
            server_process: None,
        }
    }
    
    /// 启动FTP服务器
    pub fn start_server(&mut self) -> Result<()> {
        println!("🚀 启动FTP服务器...");
        
        // 构建服务器
        let build_result = Command::new("cargo")
            .args(&["build", "-p", "ftp-server"])
            .output()?;
        
        if !build_result.status.success() {
            let error = String::from_utf8_lossy(&build_result.stderr);
            return Err(anyhow::anyhow!("构建失败: {}", error));
        }
        
        // 启动服务器进程
        let server_process = Command::new("cargo")
            .args(&["run", "-p", "ftp-server", "--", "--port", "2121"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        
        self.server_process = Some(server_process);
        
        // 等待服务器启动
        println!("⏳ 等待服务器启动...");
        thread::sleep(Duration::from_secs(3));
        
        println!("✅ FTP服务器已启动 (端口: 2121)");
        Ok(())
    }
    
    /// 停止FTP服务器
    pub fn stop_server(&mut self) -> Result<()> {
        if let Some(mut process) = self.server_process.take() {
            println!("🛑 停止FTP服务器...");
            process.kill()?;
            process.wait()?;
            println!("✅ FTP服务器已停止");
        }
        Ok(())
    }
    
    /// 运行综合测试
    pub fn run_comprehensive_test(&self) -> Result<()> {
        println!("\n🧪 运行综合测试");
        let mut test_suite = ComprehensiveTestSuite::new();
        test_suite.run_comprehensive_test()
    }
    
    /// 运行性能测试
    pub fn run_performance_test(&self) -> Result<()> {
        println!("\n⚡ 运行性能测试");
        let test_suite = PerformanceTestSuite::new();
        test_suite.run_performance_test()
    }
    
    /// 运行错误场景测试
    pub fn run_error_scenario_test(&self) -> Result<()> {
        println!("\n❌ 运行错误场景测试");
        let test_suite = ErrorScenarioTestSuite::new();
        test_suite.run_error_scenario_test()
    }
    
    /// 运行所有测试
    pub fn run_all_tests(&mut self) -> Result<()> {
        println!("🎯 开始运行所有测试");
        
        // 启动服务器
        self.start_server()?;
        
        // 运行各种测试
        self.run_comprehensive_test()?;
        self.run_performance_test()?;
        self.run_error_scenario_test()?;
        
        // 停止服务器
        self.stop_server()?;
        
        println!("🎉 所有测试完成！");
        Ok(())
    }
    
    /// 运行特定测试
    pub fn run_specific_test(&mut self, test_name: &str) -> Result<()> {
        println!("🎯 运行特定测试: {}", test_name);
        
        // 启动服务器
        self.start_server()?;
        
        match test_name {
            "comprehensive" => self.run_comprehensive_test()?,
            "performance" => self.run_performance_test()?,
            "error" => self.run_error_scenario_test()?,
            _ => return Err(anyhow::anyhow!("未知的测试名称: {}", test_name)),
        }
        
        // 停止服务器
        self.stop_server()?;
        
        println!("✅ 测试 {} 完成", test_name);
        Ok(())
    }
}

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();
    
    let mut runner = TestRunner::new();
    
    if args.len() > 1 {
        let test_name = &args[1];
        runner.run_specific_test(test_name)?;
    } else {
        runner.run_all_tests()?;
    }
    
    Ok(())
}
